<template>
  <div class="add-quality-report">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>质检报工记录信息详情页</h2>
           <el-tag :type="formData.status === '已完成' ? 'success' : 'warning'" class="status-tag">
            {{ formData.status || '待质检' }}
          </el-tag>
        </div>
      </template>
      
      <el-descriptions
        class="quality-detail"
        :column="2"
        border
        title="质检报工记录信息"
      >
        <el-descriptions-item label="工序编码">{{ formData.processCode }}</el-descriptions-item>
        <el-descriptions-item label="工序名称">{{ formData.processName }}</el-descriptions-item>
        <el-descriptions-item label="加工顺序">{{ formData.processingOrder }}</el-descriptions-item>
        <el-descriptions-item label="工艺流程">{{ formData.processFlow }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ formData.person }}</el-descriptions-item>
        <el-descriptions-item label="所在部门">{{ formData.department }}</el-descriptions-item>
        <el-descriptions-item label="报工时间">{{ formData.reportingTime }}</el-descriptions-item>
        <el-descriptions-item label="完工数量">{{ formData.quantity }}</el-descriptions-item>
        <el-descriptions-item label="生产人员">{{ formData.productionPersonnel }}</el-descriptions-item>
        <el-descriptions-item label="所在部门">{{ formData.departmentSS }}</el-descriptions-item>
        <el-descriptions-item label="报工人员">{{ formData.reportingpersonnel }}</el-descriptions-item>
        <el-descriptions-item label="合格数量">{{ formData.qualifiedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="不合格数量">{{ formData.unqualifiedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="不合格原因">{{ formData.unqualifiedReason }}</el-descriptions-item>
        <el-descriptions-item label="合格率">{{ qualifiedRate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="formData.status === '已完成' ? 'success' : 'warning'">
            {{ formData.status || '待质检' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
        qualityReportWorkid:  route.params.qualityReportWorkid,
        processCode: '',
        processName: '',
        processingOrder: '',
        processFlow: '',
        person: '',
        department: '',
        reportingTime: '',
        quantity: 0,
        productionPersonnel: '',
        departmentSS: '',
        reportingpersonnel: currentUser.value,
        qualifiedQuantity: 0,
        unqualifiedQuantity: 0,
        unqualifiedReason: null,
        status: '',
        isDel: true
  });

  // 禁用未来日期
  const disableFutureDate = (time) => {
    return time.getTime() > Date.now();
  };

  // 计算不合格数量
  const calculateUnqualifiedQuantity = () => {
    formData.unqualifiedQuantity = Math.max(0, formData.quantity - formData.qualifiedQuantity);
  };

  // 修改表单验证规则
  const rules = reactive({
    person: [
      { required: true, message: '请选择质检负责人', trigger: 'change' }
    ],
    department: [
      { required: true, message: '请选择质检部门', trigger: 'change' }
    ],
    reportingTime: [
      { required: true, message: '请选择报工时间', trigger: 'change' }
    ],
    qualifiedQuantity: [
      { required: true, message: '请输入合格数量', trigger: 'blur' },
      { type: 'number', min: 0, message: '合格数量不能小于0', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value > formData.quantity) {
            callback(new Error('合格数量不能超过完工数量'));
          } else {
            callback();
          }
        }, 
        trigger: 'blur' 
      }
    ],
    unqualifiedReason: [
      { 
        validator: (rule, value, callback) => {
          if (formData.unqualifiedQuantity > 0 && !value) {
            callback(new Error('请填写不合格原因'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  });

  const getProductionById = (qualityReportWorkid) => {
    console.log('查看反填数据:', qualityReportWorkid);
    Materialread.get('f-read/api/Arrival/FTQualityReportWork', {
        params:{
            qualityReportWorkid: route.query.qualityReportWorkid
        }
      })
      .then(res=>{
        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
          const data = res.data.data[0];
          Object.assign(formData, {
            qualityReportWorkid: data.qualityReportWorkid,
            processCode: data.processCode,
            processName: data.processName,
            processingOrder: data.processingOrder,
            processFlow: data.processFlow,
            person: data.person,
            department: data.department,
            reportingTime: data.reportingTime,
            quantity: data.quantity || 0,
            productionPersonnel: data.productionPersonnel,
            departmentSS: data.departmentSS,
            qualifiedQuantity: data.qualifiedQuantity || 0,
            unqualifiedQuantity: data.unqualifiedQuantity || 0,
            unqualifiedReason: data.unqualifiedReason,
            status: data.status,
          });
          // 计算初始不合格数量
          calculateUnqualifiedQuantity();
          console.log('反填数据:', formData);
        }
      })
      .catch(error => {
        console.error('获取数据出错:', error);
        ElMessage.error('获取数据失败');
      });
  };

  // 提交质检结果
  const submitQualityReport = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        // 更新状态为已完工
        formData.status = '已完工';
        
        // 添加确认对话框
        ElMessageBox.confirm(
          '确认提交质检结果？提交后将更新工单状态为已完工。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          Materialwrite.post('f-write/api/Arrival/UpdateQualityReportWork', formData)
            .then(response => {
              if (response.data.code === 200) {
                ElMessage.success('质检结果提交成功，状态已更新为已完工');
                router.push("/GetQualityReportWork");
              } else {
                ElMessage.error(`提交失败：${response.data.message}`);
              }
            })
            .catch(error => {
              console.error('保存出错:', error);
              ElMessage.error('保存时出现错误，请检查网络或重试');
            });
        }).catch(() => {
          ElMessage.info('已取消提交');
        });
      } else {
        ElMessage.error('请填写完整且正确的质检信息');
        return false;
      }
    });
  };

  // 重置表单
  const resetForm = () => {
    ElMessageBox.confirm(
      '确认重置表单？所有已填写的信息将被清空。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      formRef.value.resetFields();
      calculateUnqualifiedQuantity();
      ElMessage.success('表单已重置');
    }).catch(() => {
      ElMessage.info('已取消重置');
    });
  };

  const qualifiedRate = computed(() => {
    const total = Number(formData.qualifiedQuantity) + Number(formData.unqualifiedQuantity);
    if (!total) return '0%';
    return ((Number(formData.qualifiedQuantity) / total) * 100).toFixed(2) + '%';
  });

  onMounted(()=>{
    getProductionById();
  })
</script>
    
<style scoped>
.add-quality-report {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center; /* 添加这一行来居中标题 */
}

.status-tag {
  margin-left: 10px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
  color: #2c3e50;
  font-size: 18px;
}

.quality-form {
  max-width: 1200px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-date-picker,
.el-input-number {
  width: 100%;
}

.el-textarea__inner {
  min-height: 100px;
}

.el-button {
  margin-right: 15px;
  padding: 12px 24px;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>